package com.zxh.system.controller;

import com.zxh.system.domain.JsonResult;
import com.zxh.system.domain.ResultCode;
import com.zxh.system.entity.Department;
import com.zxh.system.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.Optional;

@RestController
@RequestMapping("department")
public class DepartmentController extends BaseController<Department> {

    @Autowired
    private DepartmentService departmentService;

    @PreAuthorize("hasAnyRole('ROLE_DEPARTMENT_SAVE','ROLE_ADMIN')")
    @PostMapping
    public JsonResult<Department> save(@RequestBody Department department) {
        departmentService.add(department);
        return JsonResult.EMPTY();
    }

    @PreAuthorize("hasAnyRole('ROLE_DEPARTMENT_SAVE','ROLE_ADMIN')")
    @PutMapping
    public JsonResult<Department> update(Department department) {
        departmentService.update(department);
        return JsonResult.EMPTY();
    }

    @PreAuthorize("permitAll()")
    @GetMapping("{id}")
    public JsonResult<Department> get(@PathVariable Serializable id) {
        Optional<Department> d = departmentService.get(id);
        if(d.isPresent())
            return new JsonResult<>(d.get());
        else
            return new JsonResult<>(ResultCode.NOT_DATA);
    }

    @PreAuthorize("permitAll()")
    @GetMapping("children/{id}")
    public JsonResult<Department> children(@PathVariable Serializable id){
        Optional<Department> d = departmentService.get(id);
        if(d.isPresent())
            return new JsonResult<>(d.get().getChildren());
        return JsonResult.EMPTY();
    }

    @PreAuthorize("permitAll()")
    @GetMapping("query")
    public JsonResult<Department> query(PageRequest page, Department department) {
        return new JsonResult<>(departmentService.query(page,department));
    }
}
